#include "NetComm.h"


void * NetComm::threadFunc(void *arg)
{
    int socketFd = *((int *)arg);
    int ret = 0;
    char buf[400];
    strncpy(buf,"Hello Qt,I am 6818 from Polaris",sizeof(buf));
    printf(" NetComm::threadFunc()  buf = %s\n",buf);
    write(socketFd,buf,sizeof(buf));

    ArmSysInfo *tmp_ArmSysInfo = (ArmSysInfo *)get_pShmArmSysInfo();
    

    while(1)
    {
        sleep(1);
        tmp_ArmSysInfo = (ArmSysInfo *)get_pShmArmSysInfo();
        snprintf(buf,400,"%s@%s@%s",tmp_ArmSysInfo->IpAddr,tmp_ArmSysInfo->DevName,tmp_ArmSysInfo->DevtimeStr);
        int ret = write(socketFd,buf,sizeof(buf));
        // printf("buf = %s\n",buf);
        // printf("write() return = %d\n",ret);
    }

}

int NetComm::socketAccept()
{
    int ret = 0;
    
    pthread_t p;
    

    int socketFd = socketInit();
    if(socketFd == -1)
    {
        printf("socketInit() == -1 \n");
        return -1;
    }

    struct sockaddr_in clientInfo;
    memset(&clientInfo,0,sizeof(clientInfo));
    int len = sizeof(clientInfo);

    while (1)
    {
        // accept之后，应该单独出来一个线程来跑程序，使用互斥量进行保护
        int newSocketFd = accept(socketFd,(struct sockaddr *)&clientInfo,(socklen_t *)&len);
        if(newSocketFd == -1)
        {
            printf("accept error return -1\n");
            return -1;
        }
        else
        {   
            
            pthread_create(&p,NULL,threadFunc,(void *)&newSocketFd);
            printf("accept successfully , to  %s \n",inet_ntoa(clientInfo.sin_addr));

        }

        pthread_join(p,NULL);
        printf("after pthread_join\n");
    }
    


    return 0;
}


int NetComm::socketInit()
{
    //================socket()
    int fd = socket(AF_INET,SOCK_STREAM,0);
	if(fd == -1)
	{
		printf("socket error\n");
		return -1;
	}

    //定义一个结构体来存放服务器（本机）的信息，用于bind()
	struct sockaddr_in ipAddr;
	bzero(&ipAddr,sizeof(ipAddr));
	
	ipAddr.sin_family = AF_INET;				//协议
	ipAddr.sin_port = htons(1997);				//端口号
	ipAddr.sin_addr.s_addr = htonl(INADDR_ANY);	//本机的IP地址
	
	
	//================bind()
	int ret = bind(fd,(struct sockaddr *)&ipAddr,sizeof(ipAddr));
	if(ret ==-1)
	{
		printf("bind error\n");
		return -1;
	}

    //================listen()
	ret = listen(fd,0);
	if(ret ==-1)
	{
		printf("bind error\n");
		return -1;
	}
	
	return fd;

}

